package com.ygs.secs.controller;


import com.ygs.secs.model.Enterprise;
import com.ygs.secs.service.EnterpriseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * 附件上传
 *
 * @author Yunxi
 * @date 2020.11.29
 */
@RestController
@RequestMapping("/upload")
@Configuration
@ImportResource(value = {"classpath:spring/spring-mybatis.xml"})
public class AttachmentUploadController {
    //上传图片真实路径
    @Value("${uppath}")
    String uploadPath;
    //映射路径
    @Value("${mappingpath}")
    String mappath;

    @Autowired
    EnterpriseService enterpriseService;

    /**
     * 单图片上传
     *
     * @param file 文件
     * @return 通用json返回格式
     */
    @RequestMapping("/singleImageUpload")
    public Map<String, Object> singleImageUpload(MultipartFile file, String diridentity) {
        Map<String, Object> map = new HashMap<>();
        // 判断文件是否为空，空则返回失败页面
        if (file.isEmpty()) {
            map.put("code", 500);
            map.put("msg", "文件为空，上传失败");
            map.put("data", "");
            return map;
        }
        //新建日历对象
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        String newpath = diridentity + "/" + year + "/" + month + "/";
//        System.out.println(newpath);
        // 获取文件存储路径（绝对路径）
        String path = uploadPath + newpath;
        // 获取原文件名
        String fileName = file.getOriginalFilename();
        //文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //通过UUID生成新文件名
        String newfilename = UUID.randomUUID().toString().replace("-", "") + suffix;
//        System.out.println("新文件名：" + newfilename);
        // 创建文件实例
        File filePath = new File(path, newfilename);
        // 如果文件目录不存在，创建目录
        if (!filePath.getParentFile().exists()) {
            filePath.getParentFile().mkdirs();
            System.out.println("创建目录" + filePath);
        }
        // 写入文件
        try {
            file.transferTo(filePath);
            Map<String, String> srcmap = new HashMap<>();
            map.put("code", 0);
            map.put("msg", "上传成功");
            srcmap.put("src", mappath + newpath + newfilename);
            map.put("data", srcmap);
        } catch (IOException e) {
            map.put("code", 500);
            map.put("msg", "上传失败");
            map.put("data", "");
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 企业logo上传
     *
     * @param file 文件
     * @return 通用json返回格式
     */
    @RequestMapping("/TXImageUpload")
    public Map<String, Object> TXImageUpload(MultipartFile file, String diridentity) {
        Map<String, Object> map = new HashMap<>();
        // 判断文件是否为空，空则返回失败页面
        if (file.isEmpty()) {
            map.put("code", 500);
            map.put("msg", "文件为空，上传失败");
            map.put("data", "");
            return map;
        }
        //新建日历对象
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        String newpath = diridentity + "/" + year + "/" + month + "/";
        //System.out.println(newpath);
        // 获取文件存储路径（绝对路径）
        String path = uploadPath + newpath;
        // 获取原文件名
        String fileName = file.getOriginalFilename();
        //文件后缀
        String suffix = ".jpg";
        //通过UUID生成新文件名
        String newfilename = diridentity + suffix;
//        System.out.println("新文件名：" + newfilename);
        // 创建文件实例
        File filePath = new File(path, newfilename);
        // 如果文件目录不存在，创建目录
        if (!filePath.getParentFile().exists()) {
            filePath.getParentFile().mkdirs();
            System.out.println("创建目录" + filePath);
        }
        // 写入文件
        try {
            Enterprise enterprise = enterpriseService.selectByPrimaryKey(diridentity);
            enterprise.setLogoimg(mappath + newpath + newfilename);
            enterpriseService.updateByPrimaryKey(enterprise);
            file.transferTo(filePath);
            Map<String, String> srcmap = new HashMap<>();
            map.put("code", 0);
            map.put("msg", "上传成功");
            srcmap.put("src", mappath + newpath + newfilename);
            map.put("data", srcmap);
        } catch (IOException e) {
            System.out.println("fail");
            map.put("code", 500);
            map.put("msg", "上传失败");
            map.put("data", "");
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 简历上传
     *
     * @param file        简历文件
     * @param diridentity 文件夹名(学号)
     * @return
     */
    @RequestMapping("/resumeUpload")
    public Map<String, Object> resumeUpload(MultipartFile file, String diridentity) {
        Map<String, Object> map = new HashMap<>();
        // 判断文件是否为空，空则返回失败页面
        if (file.isEmpty()) {
            map.put("code", 500);
            map.put("msg", "文件为空，上传失败");
            map.put("data", "");
            return map;
        }

        String newpath = diridentity + "/resume/";
//        System.out.println(newpath);
        // 获取文件存储路径（绝对路径）
        String path = uploadPath + newpath;
        // 获取原文件名
        String fileName = file.getOriginalFilename();
        //文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //通过学号生成新文件名
        String newfilename = UUID.randomUUID().toString().replace("-", "") + suffix;
        //System.out.println("新文件名：" + newfilename);
        // 创建文件实例
        File filePath = new File(path, newfilename);
        // 如果文件目录不存在，创建目录
        if (!filePath.getParentFile().exists()) {
            filePath.getParentFile().mkdirs();
            System.out.println("创建目录" + filePath);
        }
        // 写入文件 resumeName
        try {
            file.transferTo(filePath);
            Map<String, String> srcmap = new HashMap<>();
            map.put("code", 200);
            map.put("msg", "上传成功");
            srcmap.put("src", mappath + newpath + newfilename);
            map.put("data", srcmap);
        } catch (IOException e) {
            map.put("code", 500);
            map.put("msg", "上传失败");
            map.put("data", "");
            e.printStackTrace();
        }
        return map;
    }

}
